package com.nintendo.exception;

import com.nintendo.response.Result;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;

@RestControllerAdvice
public class GlobalExceptionHandler {

    public ResponseEntity<Result> handleBindException(BindException e) {
        Result result = validationException(e);
        return ResponseEntity.badRequest().body(result);
    }
    @ExceptionHandler(BindException.class)

    private Result validationException(BindException e) {
        BindingResult bindingResult = e.getBindingResult();

        if (bindingResult.hasErrors()) {
            StringBuilder errorMessage = new StringBuilder();

            for (FieldError error : bindingResult.getFieldErrors()) {
                errorMessage.append(error.getField()).append(error.getDefaultMessage()).append("\n");
            }

            return Result.error(errorMessage.toString().trim());
        }
        return Result.error("Unknown validation error");
    }
}
